﻿using SqlSugar;
using XinLife.Application.Interface;
using XinLife.Model;

namespace XinLife.Application.Implement
{
    public class AuthorizeService : BaseService, IAuthorizeService
    {
        public AuthorizeService(IBaseRepository baseRepositor) : base(baseRepositor) { }

        public async Task<List<Authorize>> GetRoleModule()
        {
            var roleModulePermissions = await _db.Queryable<Authorize>().Where(t => t.cItemType == 2).ToListAsync();
            if (roleModulePermissions.Count > 0)
            {
                var roles = await _db.Queryable<Role>().ToListAsync();
                var modulebuttons = await _db.Queryable<ModuleButton>().ToListAsync();

                foreach (var item in roleModulePermissions)
                {
                    item.Role = roles.Where(t => t.cId == item.cObjectId).FirstOrDefault();
                    item.ModuleButton = modulebuttons.Where(t => t.cId == item.cItemId).FirstOrDefault();
                }
            }
            return roleModulePermissions;
        }

        public async Task<User> GetUser(string userId)
        {
            var user = await _db.Queryable<User>().Where(t => t.cId == userId).FirstAsync();
            user.Roles = await _db.Queryable<Role>().Where(a => SqlFunc.Subqueryable<UserRole>().Where(b => b.cRoleId == a.cId && b.cUserId == user.cId).Any()).ToListAsync();

            return user;
        }
    }
}
